import { getToken, setToken, removeToken } from '@/utils/auth'
import storage from '@/utils/storage'
import store from '@/store'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo:  storage.get("USER_INFO"),
    roles: [],
    permissions: []    
  }
}

const state = getDefaultState()

const mutations = {
  SET_TOKEN: (state, token) => {
	setToken(token)
    state.token = token
  },
  SET_USERINFO: (state, userInfo) => {
	storage.save('USER_INFO', userInfo)
    state.userInfo = userInfo
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  }    
}

const actions = {
  // 登录
  Login({ dispatch, commit }, userInfo) {
    const username = userInfo.username.trim()
    const password = userInfo.password
    return new Promise((resolve, reject) => {		
	  uni.$u.api.login.mobileLogin({username, password}).then(res => {
		  commit('SET_TOKEN', res.token)
		  dispatch("getUserInfo");
		  resolve();
	  })
    })
  },
    
  // 获取用户信息
  getUserInfo({ dispatch, commit, state }) {
    return new Promise((resolve, reject) => {
      uni.$u.api.login.getUserInfo().then(res => {
        const user = res.user
        user.avatar = (user.avatar == "" || user.avatar == null) ? require("@/static/imgs/head.png") : store.state.config.baseFileUrl + user.avatar;
        if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
          commit('SET_ROLES', res.roles)
          commit('SET_PERMISSIONS', res.permissions)
        } else {
          commit('SET_ROLES', ['ROLE_DEFAULT'])
        }
        commit('SET_USERINFO', user)
		
		//获取用户路由
		store.dispatch("menu/userMenus");

        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
    
  // 退出系统
  LogOut({ commit, state }) {
    return new Promise((resolve, reject) => {
      uni.$u.api.login.logout(state.token).then(() => {
		storage.clear();
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_PERMISSIONS', [])
		commit('SET_USERINFO', {})
        removeToken()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
    
  // 前端 登出
  FedLogOut({ commit }) {
    return new Promise(resolve => {
      storage.clear();
      commit('SET_TOKEN', '')
	  commit('SET_USERINFO', {})
      removeToken()
      resolve()
    })
  }      
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

